﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Core;
using System.IO;
using SmartSapce.ServiceLocation;

namespace SmartSpace.WebApp._console.core
{
    public partial class application_add : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            _ctlLinkBack.NavigateUrl = "./application-list.aspx";
            if (!IsPostBack)
            {
                ICoreService service = ServiceLocator.Get<ICoreService>();
                _ctlListTemplate.DataSource = service.GetSiteTemplates();
                _ctlListTemplate.DataBind();
            }
        }

        protected void _ctlBtnSave_Click(object sender, EventArgs e)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();
            Guid themeId = new Guid(_ctlListTemplate.SelectedValue);

            if (_ctlFileImage.HasFile)
            {
                SmartSpace.Core.Image image = new SmartSpace.Core.Image();
                image.Id = Guid.NewGuid();
                image.Data = _ctlFileImage.FileBytes;
                image.Caption = _ctlFileImage.FileName;
                image.Extension = new FileInfo(_ctlFileImage.FileName).Extension;

                if (service.SaveImage(image))
                {
                    Site app = new Site();
                    app.Id = Guid.NewGuid();
                    app.HostUrl = _ctlEditHostUrl.Text;
                    app.Title = _ctlEditText.Text;
                    app.ImageId = image.Id;
                    SiteTemplate theme = service.GetSiteTemplate(themeId);
                    app.TemplateId = theme.Id;
                    app.Type = theme.Type;
                    app.Copyright = _ctlEditCopyright.Text;
                    service.SaveSite(app);

                    Response.Redirect(_ctlLinkBack.NavigateUrl);
                }
            }
            else
            {
            }
        }
    }
}